package com.cyx.friend.service.user.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cyx.common.core.constants.Constants;
import com.cyx.common.core.domain.TableDataInfo;
import com.cyx.common.core.enums.ExamListType;
import com.cyx.common.core.enums.ResultCode;
import com.cyx.common.core.utils.ThreadLocalUtil;
import com.cyx.common.security.exception.ServiceException;
import com.cyx.common.security.service.TokenService;
import com.cyx.friend.domain.exam.Exam;
import com.cyx.friend.domain.exam.dto.ExamDTO;
import com.cyx.friend.domain.exam.dto.ExamQueryDTO;
import com.cyx.friend.domain.exam.vo.ExamVO;
import com.cyx.friend.domain.user.UserExam;
import com.cyx.friend.manager.ExamCacheManager;
import com.cyx.friend.mapper.exam.ExamMapper;
import com.cyx.friend.mapper.user.UserExamMapper;
import com.cyx.friend.service.user.IUserExamService;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserExamServiceImpl implements IUserExamService {

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private UserExamMapper userExamMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ExamCacheManager examCacheManager;

//    @Value("$jwt.secret")
//    private String secret;

    @Override
    public int enter(String token, ExamDTO examDTO) {
        Long examId = examDTO.getExamId();
        Exam exam = examMapper.selectById(examId);
        if(exam == null) {
            throw new ServiceException(ResultCode.EXAM_NOT_EXISTS);
        }
        if(exam.getStatus() == 0) {
            throw new ServiceException(ResultCode.EXAM_NOT_PUBLISH);
        }
        if(exam.getStartTime().isBefore(LocalDateTime.now())) {
            throw new ServiceException(ResultCode.EXAM_STARTED);
        }
//        Long userId = tokenService.getUserId(token, secret);
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        UserExam userExam = userExamMapper.selectOne(new LambdaQueryWrapper<UserExam>()
                .eq(UserExam::getExamId, examId)
                .eq(UserExam::getUserId, userId));
        if(userExam != null) {
            throw new ServiceException(ResultCode.EXAM_IS_HAS_ENTERED);
        }
        examCacheManager.addUserExamCache(userId, examId);
        userExam = new UserExam();
        userExam.setExamId(examId);
        userExam.setUserId(userId);
        return userExamMapper.insert(userExam);
    }

    @Override
    public TableDataInfo list(ExamQueryDTO examQueryDTO) {
        // 从redis中获取数据并返回
        // 先获取redis中数据的总数
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        Integer examListType = ExamListType.USER_EXAM_LIST.getValue();
        Long total = examCacheManager.getListSize(examListType, userId);
        List<ExamVO> examVOList;
        // 判断redis中是否有数据
        if(total == null || total <= 0) {
            // 如果redis中没有数据，从数据库中查询数据
            examVOList = userExamMapper.selectUserExamList(examQueryDTO, userId);
            // 刷新缓存，将数据库数据同步到redis 中
            examCacheManager.refreshCache(examQueryDTO, userId);
            total = new PageInfo<>(examVOList).getTotal();
        } else {
            examVOList = examCacheManager.getExamVOList(examQueryDTO, userId);
            // 如果是正常情况，redis中的数据和数据库中一致，不需要操作
            // 但是，如果在获取数据时，发现数据异常，那么就需要重新刷新缓存，刷新缓存之后，total可能会变，所有要重新获取一下
            total = examCacheManager.getListSize(examListType, userId);
        }
        if(CollectionUtil.isEmpty(examVOList)){
            return TableDataInfo.empty();
        }
        // 获取符合查询条件的总记录数
        return TableDataInfo.success(examVOList, total);
    }
}
